/*
 * 表格控制器
 */
var app = angular.module('myApp', ['angularFileUpload', 'moment-picker', 'daterangepicker']);
app.controller('mainSelfCtrl', ['$scope', '$http', function GridSelfController($scope, $http){}]);
app.config(['momentPickerProvider', function (momentPickerProvider) {
	momentPickerProvider.options({
		locale:"zh-cn",
		today: true
	});
}])
app.controller('mainCtrl', ['$scope', '$http', MainController]);
function MainController($scope, $http){
	$scope.pagination = {
		'currentSize': 50,
		'currentPage': 1,
		'optionArr': [{'size': 50, 'name':'每页50条'}, {'size': 100, 'name':'每页100条'}, {'size': 500, 'name':'每页500条'}, {'size': 9999, 'name':'每页1W条'}],
		'totalPage': 0,
		'totalNum': 1,
		'pagerArr': [{'num': 1},{'num': 2},{'num': 3},{'num': 4},{'num': 5}]
	}; // 分页配置
	$scope.menuId = dto.menuId; // 菜单ID
	$scope.templateType = 1; // 模板类型，1普通列表2左树右列表
	$scope.pathGridRequest = dto.pathGridRequest; // 表格请求地址
	$scope.conditionArr = dto.conditionArr; // 条件数组
	$scope.buttonArr = dto.buttonArr; // 按钮数组
	$scope.MAP_DICT = MAP_DICT; // 字典MAP
	
	$scope.colArr = dto.colArr; // 字段数组
	
	console.log('----conditionArr----', $scope.conditionArr);
	console.log('----colArr----', $scope.colArr);
	
	// 处理样式
	for (var i = 0; i < $scope.colArr.length; i++) {
		var col = $scope.colArr[i];
		$scope.colArr[i].style = {'text-align': col.align};
	}
	// 处理左固定
	var currentLeft = 51;
	for (var i = 0; i < $scope.colArr.length; i++) {
		var col = $scope.colArr[i];
		if (col.fixed == 'left') {
			$scope.colArr[i].style.left = currentLeft + 'px';
			currentLeft = currentLeft + col.width;
			console.log('currentLeft--', currentLeft);
		}
	}
	// 处理右固定
	var currentRgt = 0;
	for (var i = $scope.colArr.length - 1; i >= 0; i--) {
		var col = $scope.colArr[i];
		if (col.fixed == 'right') {
			$scope.colArr[i].style.right = currentRgt + 'px';
			//$scope.colArr[i].style = {'right': currentRgt + 'px', 'text-align': col.align};
			currentRgt = currentRgt + col.width;
			console.log('currentRgt--', currentRgt);
		}
	}
	console.log('colArr---', $scope.colArr);
	$scope.selectAllState = false; // 全选状态默认
	
	$scope.extraCond = {}; // 额外搜素条件
	
	/*
	* 树基本配置
	*/
	$scope.tree = {
		icons_top: [], // 顶部图标，格式如：[{'title': '新增', 'event': 'add', 'icon': 'icon-plus-circle-fill'}]
		nodeClickExCo: false, // 节点点击是否展开或折叠
		data:[],
		defaultExpand: false // 默认节点是否展开，false否true是
	};
	
	/*
	* 树节点点击事件
	*/
	$scope.tree.nodeClick = function(item) {
		item.status = !item.status; // 节点伸缩
	}
	/*
	* 树顶部图标点击事件
	*/
	$scope.tree.clickTop = function(event) {
		console.log(event);
	}
	
	/*
	* 表格基本配置
	*/
	$scope.grid = {
		checkAllState: false
	};
	
	/*
	* 列表全选或反选
	*/
	$scope.grid.checkAll = function() {
		console.log('---------$scope.grid.checkAllState--------------', $scope.grid.checkAllState);
		
		// 处理每条数据的选中状态
		for(var i = 0; i < $scope.rows.length; i++) {
			$scope.rows[i]['checked'] = $scope.grid.checkAllState;
		}
	}
	
	/*
	* 额外条件变更
	*/
	$scope.changeExtraCond = function(extraCond) {
		$scope.extraCond = extraCond;
	}
	
	$scope.modalLink = {} // 链接弹出框
	
	/*
	* 显示链接弹出框
	*/
	$scope.showModalLink = function(url, title) {
		$scope.modalLink.bsObj = window.bsModalLinkObj
		document.getElementById('modal_link_iframe').src = url;
		$scope.modalLink.title = title;
		$scope.modalLink.bsObj.show();
	}
	
	/*
	* 显示图片弹出框
	*/
	$scope.showModalImg = function(url) {
		
		layer.photos({photos: {'title': '','id': '','start': 0,'data': [{'src': url}]},closeBtn: 1});
		
		return;
	}
	
	/*
	 * 确认框
	 */
	$scope.showModalConfirm = function(config) {
		$scope.confirm.tip = config.tip;
		$scope.confirm.ok = config.ok;

		$scope.confirm.bsObj = new bootstrap.Modal(document.getElementById('modal_confirm'), {
			keyboard: false
		});
		
		$scope.confirm.bsObj.show();
	}
	
	/*
	* 显示弹出框(下拉选择)
	*/
	$scope.showModalDropdown = function(config) {
		$scope.dropdown = {};
//		$scope.dropdown.tip = config.tip;
//		$scope.dropdown.ok = config.ok;

		$scope.dropdown.bsObj = new bootstrap.Modal(document.getElementById('modal_dropdown'), {
			keyboard: false
		});
		
		$scope.dropdown.bsObj.show();
	}
	
	/*
	* 定义加载具体页面函数
	*/
	$scope.loadPage = function(pageNo) {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		
		var params = Object.assign({page: pageNo, size: $scope.pagination.currentSize, conditionss: JSON.stringify($scope.conditionArr)}, $scope.extraCond);

		$http.post($scope.pathGridRequest, {}, {params: params})
		.success(function (response) {
			if(response.code == 0) {
				$scope.selectAllState = false; // 全选状态取消
				$scope.pagination.currentPage = pageNo;
				
				console.log(response);
				$scope.rows = response.data;
				
				// 更新分页数据
				$scope.pagination.totalNum = response.count;
				$scope.pagination.totalPage = Math.floor(($scope.pagination.totalNum + $scope.pagination.currentSize - 1) / $scope.pagination.currentSize);
				for(var i = 0; i < 5 && i < $scope.pagination.totalPage; i++) {
					if($scope.pagination.currentPage < 3) {
						$scope.pagination.pagerArr[i].num = i + 1;
					} else if($scope.pagination.currentPage > $scope.pagination.totalPage - 3) {
						$scope.pagination.pagerArr[i].num = $scope.pagination.totalPage - 4 + i;
					} else {
						$scope.pagination.pagerArr[i].num = $scope.pagination.currentPage - 2 + i;
					}
				}
			}
			layer.close(indexOfLoading);
		});
	}
	
	/*
	 * 导出数据
	 */
	$scope.doExport = function(url) {
		$http.post(url, {}, {params: {conditionss: JSON.stringify($scope.conditionArr)}})
		.success(function (response) {
			if (response.code == 0) {
				if(response.msg != undefined && response.msg.startsWith('http')) {
					window.open(response.msg);
				} else {
					layer.msg(response.msg);
				}
			} else {
				alert(response.msg);
			}
		});
	}
	
	/*
	* 删除
	* 传给服务端的参数是ids，格式如：1,2,3
	*/
	$scope.doDelete = function(url, datas) {
		if(datas.length == 0) {
			layer.alert('尚未选中数据');
		} else {
			layer.confirm('确定要删除吗？', {icon: 3}, function () {
				layer.msg('处理中', {
					icon: 16,shade: 0.01
				});

				var ids = '';
				for(var i = 0 ;i < datas.length; i++){
					ids = ids + datas[i].id + ',';
				}
				$http.post(url, {}, {params: {ids: ids.substring(0, ids.length - 1)}})
				.success(function (response) {
					if (response.code == 0) {
						layer.msg(response.msg);
					} else {
						alert(response.msg);
					}
				});

			}, function () {});
		}
		
	}
	
	/*
	 * 获取选中的数据列表
	 */
	$scope.getSelectedRows = function() {
		var rows = [];
		for(var i = 0; i < $scope.rows.length; i++) {
			if ($scope.rows[i].checked) {
				rows.push($scope.rows[i]);
			}
		}
		return rows;
	}
	
	/*
	 * 清空查询条件
	 */
	$scope.clearConditions = function() {
		// 处理每条数据的选中状态
		for(var i = 0; i < $scope.conditionArr.length; i++) {
			$scope.conditionArr[i].value = '';
		}
	}
	
	/*
	 * 单选弹出框配置
	 */
	$scope.radio = {
			rows: [],
			pagination: {
				'currentSize': 50,
				'currentPage': 1,
				'optionArr': [{'size': 50, 'name':'每页50条'}, {'size': 100, 'name':'每页100条'}, {'size': 500, 'name':'每页500条'}, {'size': 9999, 'name':'每页1W条'}],
				'totalPage': 0,
				'totalNum': 1,
				'pagerArr': [{'num': 1},{'num': 2},{'num': 3},{'num': 4},{'num': 5}]
			}
	}; // 单选弹出框数据数组初始置为空
	
	/*
	 * 复选弹出框配置
	 */
	$scope.checkbox = {
			rows: [],
			pagination: {
				'currentSize': 50,
				'currentPage': 1,
				'optionArr': [{'size': 50, 'name':'每页50条'}, {'size': 100, 'name':'每页100条'}, {'size': 500, 'name':'每页500条'}, {'size': 9999, 'name':'每页1W条'}],
				'totalPage': 0,
				'totalNum': 1,
				'pagerArr': [{'num': 1},{'num': 2},{'num': 3},{'num': 4},{'num': 5}]
			},
			afterSelectDatas:function(rowsSelected) {console.log(111);}
	};
	
	/*
	 * 多选弹出框数据数组初始置为空
	 */
	$scope.multy = {
			rows: []
	};
	
	/*
	 * 确认弹出框
	 */
	$scope.confirm = {
	}
	
	// 初始加载第一页
	$scope.loadPage(1);
	
	/*
	* 显示单选弹出框
	* modalKey 弹出框唯一KEY
	* type 类型，1表单用2子列表用3其它
	* code 关联的字段编码
	* subIndex 所在的子列表序号
	*/
	$scope.showModalRadio = function(modalKey, type, code, subIndex, conditionsDefault) {
		$scope.radio.type = type;
		$scope.radio.code = code;
		$scope.radio.subIndex = subIndex;
		if(modalKey == undefined || modalKey == null || modalKey == '') {
			layer.msg('单选弹出框KEY值尚未配置');
			return;
		}
		if(type == 2 && (subIndex == undefined || subIndex == null)) {
			layer.msg('子列表所在行号尚未配置');
			return;
		}
		$scope.radio.bsObj = new bootstrap.Modal(document.getElementById('modal_radio'), {
			keyboard: false
		});
		
		var res = MAP_MODAL[modalKey];
		console.log(modalKey);
		console.log(res);
		$scope.radio.conditions = res.conditions; // 查询条件数组
		// 处理默认条件
		if(conditionsDefault) {
			for (var i = 0; i < conditionsDefault.length; i++) {
				var conditionDefault = conditionsDefault[i];
				for (var j = 0; j < $scope.radio.conditions.length; j++) {
					if (conditionDefault['code'] == $scope.radio.conditions[j]['code']) {
						$scope.radio.conditions[j]['value'] = conditionDefault['value'];
					}
				}
			}
		}
		
		$scope.radio.colArr = res.colGrids; // 字段数组
		$scope.radio.pathGridRequest = res.pathGridRequest; // 弹出框数据请求路径
		$scope.radio.loadModalRadioGrid(1);
		
		$scope.radio.bsObj.show();
	}
	
	/*
	 * 加载单选弹出框列表数据
	 */
	$scope.radio.loadModalRadioGrid = function(pageNo) {
		console.log('-------$scope.radio.conditions---------', $scope.radio.conditions);
		$http.post($scope.radio.pathGridRequest, {}, {params: {page: pageNo, size: $scope.radio.pagination.currentSize, conditionss: JSON.stringify($scope.radio.conditions)}})
		.success(function (response) {
			if(response.code == 0) {
				console.log(response);
				$scope.radio.pagination.currentPage = pageNo;
				
				$scope.radio.rows = response.data;
				
				// 更新分页数据
				$scope.radio.pagination.totalNum = response.count;
				$scope.radio.pagination.totalPage = Math.floor(($scope.radio.pagination.totalNum + $scope.radio.pagination.currentSize - 1) / $scope.radio.pagination.currentSize);
				for(var i = 0; i < 5 && i < $scope.radio.pagination.totalPage; i++) {
					if($scope.radio.pagination.currentPage < 3) {
						$scope.radio.pagination.pagerArr[i].num = i + 1;
					} else if($scope.radio.pagination.currentPage > $scope.radio.pagination.totalPage - 3) {
						$scope.radio.pagination.pagerArr[i].num = $scope.radio.pagination.totalPage - 4 + i;
					} else {
						$scope.radio.pagination.pagerArr[i].num = $scope.radio.pagination.currentPage - 2 + i;
					}
				}
			}
		});
	}
	
	/*
	 * 单选弹出框选中数据后的操作(自定义)
	 */
	$scope.doSelectRadioBySelf = function(data) {
		console.log('-------data---------', data);
	}
	
	/*
	* 格式化浮点数
	*/
	$scope.toFix = function(number, precision) {
		if (Number.isInteger(Number(number))) {
			return number;
		}
		number = Math.round(+number + 'e' + precision) / Math.pow(10, precision) + '';
		let s = number.split('.');
		if ((s[1] || '').length < precision) {
			s[1] = s[1] || '';
			s[1] += new Array(precision - s[1].length).fill('0').join('');
		}
		return s.join('.');
	}
	
	/*
	 * 进入表单页
	 */
	$scope.toFlow = function(bid, title) {
		console.log('----bid---', bid);
		$http.post('/api/inter/ysProcInst/getMenuIdByBid', {}, {params: {bid: bid}})
		.success(function (response) {
			if (response.code == 0) {
				console.log(response);
				var menuId = null;
				if (response.code == 0) {
					menuId = response.data;
				} else {
					alert('加载页面失败，请检查菜单的流程配置');
				}
				/*
				 * 此处根据不同菜单ID，跳转不同的表单页
				 */
				if (menuId == 51) {//运营公司备案
					openUrl(title,"/web/hr/thrOperateCompanyBeian/toEdit?bid="+bid);
				} else if (menuId == 70) {
					openUrl(title, '/web/finance/tcwRunningBack/toFlow?bid=' + bid);
				} else if (menuId == 10166) {//印章申请
					openUrl(title, '/web/administration/webAdmUseSignetApplyController/toEdit?bid=' + bid);
				} else if (menuId == 10169) {
					openUrl(title, '/web/business/tpProductBq/toEdit?bid=' + bid);
				} else if(menuId == '10178'){
					openUrl(title, '/web/business/tpProductActiveSq/toEdit?bid=' + bid);
				} else if(menuId == '10180'){
					openUrl(title, '/web/business/tpAplusSq/toEdit?bid=' + bid);
				} else if (menuId == 10199) {
					openUrl(title, '/web/storage/tccAllocate/toFlow?bid=' + bid);
				} else if (menuId == 10201) {//运营人员登记
					openUrl(title, '/web/hr/thrOperateRegistration/toEdit?bid=' + bid);
				} else if (menuId == 10205) {//人员申请
					openUrl(title, ' /web/hr/thrUserEntryApply/toEdit?bid=' + bid);
				} else if (menuId == 10206) {
					openUrl(title, '/web/storage/tccDistribute/toFlow?bid=' + bid);
				} else if (menuId == 10207) {
					openUrl(title, '/web/storage/tccAllocateCancel/toFlow?bid=' + bid);
				} else if (menuId == 10258) {
					openUrl(title, '/web/hr/twlStockBorrow/toFlow?bid=' + bid);
				} else if (menuId == 10263) {
					openUrl(title, '/web/base/tbUserMonthPerformanceReport/toEdit?bid=' + bid);
				} else if (menuId == 10264) {//员工工资申请单
					openUrl(title, '/web/base/tbUserPayApply/toEdit?bid=' + bid);
				} else if (menuId == 10269) {//工资付款单
					openUrl(title, '/web/base/tbPayrollSlip/toEdit?bid=' + bid);
				} else if (menuId == 10270) {//医保付款单
					openUrl(title, '/web/base/tbMedicarePay/toEdit?bid=' + bid);
				} else if (menuId == 10271) {//社保付款单
					openUrl(title, '/web/base/tbSocialSecurityPay/toEdit?bid=' + bid);
				} else if (menuId == 10272) {//公积金付款单
					openUrl(title, '/web/base/tbReservedPay/toEdit?bid=' + bid);
				} else if (menuId == 10273) {//个税付款单
					openUrl(title, '/web/base/tbIncomePay/toEdit?bid=' + bid);
				} else if (menuId == 10213) {//招商信息申请
					openUrl(title,"/web/business/thrCanvassApply/toEdit?bid="+bid);
				} else if (menuId == 10282) {//预支账户充值单
					openUrl(title, '/web/account/tcwAdvanceAccountRecharge/toEdit?bid=' + bid);
				} else if (menuId == 10283) {//预支账户报销单
					openUrl(title, "/web/account/tcwAdvanceAccountReimbursement/toEdit?bid=" + bid);
				} else if (menuId == 10291) {//预支账户归还单
					openUrl(title, '/web/account/tcwAdvanceAccountBack/toEdit?bid=' + bid);
				} else if(menuId == '10296'){//资金登记单
					openUrl(title, '/web/finance/tcwCapitalRegister/toAdd?bid=' + bid);
				} else if(menuId == '10298'){//透明计划申报
					openUrl(title, '/web/hr/thrTransparencyProgram/toEdit?bid=' + bid);
				} else if(menuId == '10306'){//预付款认领单
					openUrl(title, '/web/finance/tcwCapitalBusinessCost/toEdit?bid=' + bid);
				} else if(menuId == '10310'){//收款平台账号管理
					openUrl(title, '/web/finance/tcwDepositPlatform/toEdit?id=' + id);
				} else if(menuId == '10312'){//资金认领单
					openUrl(title, '/web/finance/tcwCapitalClaim/toEdit?bid=' + bid);
				} else if(menuId == '10320'){//万里汇提款单
					openUrl(title, '/web/finance/tcwWanliDrawing/toEdit?bid=' + bid);
				} else if(menuId == '10321'){// VAT申报
					openUrl(title, '/web/hr/thrVatApply/toFlow?bid=' + bid);
				} else if(menuId == '10322'){// 预付款退回申请
					openUrl(title, '/web/finance/tcwPaymentReturn/toEdit?bid=' + bid);
				} else if(menuId == '10327'){//万里汇预付款退回
					openUrl(title, '/web/finance/tcwWanliPaymentReturn/toEdit?bid=' + bid);
				} else if(menuId == '10330'){//万里汇提款单
					openUrl(title, '/web/business/tbBaseInfo/toEdit?id=' + id);
				} else if(menuId == '10331'){//万里汇补账单
					openUrl(title, '/web/finance/tcwWanliSupplementary/toEdit?bid=' + bid);
				} else if(menuId == '10332'){//万里汇预付款入账单
					openUrl(title, '/web/finance/tcwWanliPrepaymentRecorded/toEdit?bid=' + bid);
				} else if(menuId == '10334'){//万里汇外币付款单
					openUrl(title, '/web/finance/tcwWanliOtherPayment/toFlow?bid=' + bid);
				} else if(menuId == '10335'){//万里汇预付款对账单
					openUrl(title, '/web/finance/tcwWanliReconciliation/toFlow?bid=' + bid);
				} else if(menuId == '10352'){//职能费用申请
					openUrl(title, '/web/finance/tcwRoleCostApply/toEdit?bid=' + bid);
				} else if(menuId == '10353'){//付款申请单
					openUrl(title, '/web/finance/tcwPaymentApply/toEdit?bid=' + bid);
				} else if(menuId == '10362'){//费用结算返还单
					openUrl(title, '/web/finance/tcwExpenseSettleReturn/toEdit?bid=' + bid);
				} else if(menuId == '10368'){//采购合同单
					openUrl(title,'/web/purchase/tcgPurchaseContract/toEdit?bid=' + bid);
				} else if(menuId == '10370'){//预约采购单
					openUrl(title,'/web/purchase/tcgPurchaseAppointOrder/toEdit?bid=' + bid);
				} else if(menuId == '10371'){//采购预入库
					openUrl(title,'/web/purchase/tcgPurchasePreStorage/toEdit?bid=' + bid);
				} else if(menuId == '10385'){//发票预核销单
					openUrl(title,'/web/purchase/tcgInvoiceOffset/toEdit?bid=' + bid);
				} else if(menuId == '10387'){//采购付款单
					openUrl(title,'/web/purchase/tcgPurchasePayment/toEdit?bid=' + bid);
				} else if(menuId == '10392'){//报关单
					openUrl(title,'/web/logistics/tlCustomsDeclaration/toEdit?bid=' + bid);
				} else {
					alert('请先设置好表单页面路径');
				}
			} else {
				alert(response.msg);
			}
		});
	}
}

/**
 * 打开新页面
 * @param title
 * @param url
 * @param toType 打开页面方式，1标签页2新页面
 * @returns
 */
function openUrl(title, url, toType) {
	
	if (!window.top.is_on_1_5) {
		window.open(url);
	} else {
		window.top.add_tab(title, url);
	}
}